package com.example.beryl.Util;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.core.content.FileProvider;

import com.example.beryl.R;
import com.example.beryl.WelecomePage;
import com.example.beryl.entity.Action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 版本升级管理类
 */
public class UpdateManager {
    //应用程序Context；
    private Context mContext;
    // 是否是最新的应用,默认为false
    private boolean isNew = false;
    private boolean intercept = false;
    // 下载安装包的网络路径
    private String apkUrl = "http://172.168.1.253:9000/AppUpdate/"
            + "Beryl_debug.apk";
    private String getApkUrl = "http://192.168.10.100:8090/AppUpdate/"
            + "Beryl_debug.apk";


//    private String apkUrl = "http://192.168.1.240:8090/AndroidUpdate_test/"
//            + "Beryl_debug.apk";
    // 保存APK的文件夹
    private static final String savePath = "/storage/emulated/0/";
    private static final String saveFileName = savePath
            + "Beryl_debug.apk";
    // 下载线程
    private Thread downLoadThread;
    private int progress;// 当前进度
    TextView text;
    //进度条与通知UI刷新的handler和msg
    private ProgressBar mProgress;
    private static final int DOWN_UPDATE = 1;
    private static final int DOWN_OVER = 2;

    public UpdateManager(Context context) {
        mContext = context;
    }

    //管理类主方法
    public void checkUpdateInfo() {
        //如果Version版本号与数据库的版本号一致
        //需要查询数据库
       // if (isNew) {
           // return;
        //} else {
            showUpdateDialog();
        //}
    }

    private String IPName()
    {
        String ret = apkUrl;
        String MAC  = HandlePublic.readLogFile(Action.IpGateWay,Action.IpGateWay);
        if (MAC != "")
        {
            if (MAC.equals("192.168.10.1"))
            {
                ret = getApkUrl;
            }
        }
        return ret;
    }

    private void showUpdateDialog() {
//        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
//        builder.setTitle("软件版本更新");
//        builder.setMessage("正在更新软件包，请勿退出，更新完成后请点击打开");
        showDownloadDialog();
        //builder.create().show();
    }

    private void showDownloadDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("软件版本更新");
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.progressbar, null);
        mProgress = (ProgressBar) v.findViewById(R.id.progress);
        builder.setView(v);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                intercept = true;
            }
        });
        builder.show();
        downloadApk();
    }

    //从服务器下载APK安装包
    private void downloadApk() {
        downLoadThread = new Thread(mdownApkRunnable);
        downLoadThread.start();
    }

    private Runnable mdownApkRunnable = new Runnable() {

        @Override
        public void run() {
            URL url;
            try {
                url = new URL(IPName());
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                conn.connect();
                int length = conn.getContentLength();
                InputStream ins = conn.getInputStream();
                File file = new File(savePath);
                if (!file.exists()) {
                    file.mkdir();
                }
                File apkFile = new File(saveFileName);
                FileOutputStream fos = new FileOutputStream(apkFile);
                int count = 0;
                byte[] buf = new byte[1024];
                while (!intercept) {
                    int numread = ins.read(buf);
                    count += numread;
                    progress = (int) (((float) count / length) * 100);

                    // 下载进度
                    mHandler.sendEmptyMessage(DOWN_UPDATE);
                    if (numread <= 0) {
                        // 下载完成通知安装
                        mHandler.sendEmptyMessage(DOWN_OVER);
                        break;
                    }
                    fos.write(buf, 0, numread);
                }
                fos.close();
                ins.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    /**
     * 安装APK内容
     */
    private void installAPK() {
//        File apkFile = new File(saveFileName);
//        if (!apkFile.exists()) {
//            return;
//        }
//        Intent intent = new Intent(Intent.ACTION_VIEW);
//        intent.setDataAndType(Uri.parse("file://" + apkFile.toString()),
//                "application/vnd.android.package-archive");
//        mContext.startActivity(intent);
        File apkFile = new File(saveFileName);
        if (!apkFile.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        apkFile = new File(saveFileName);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){

            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            Uri contentUri = FileProvider.getUriForFile(mContext, "com.example.beryl.provider", apkFile);

            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");

        }else{
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");

        }
        mContext.startActivity(intent);
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {

                case DOWN_UPDATE:
                    mProgress.setProgress(progress);
                    break;
                case DOWN_OVER:
                    installAPK();
                    break;
                default:
                    break;
            }
        }

    };

}
